package com.dalin.platform.autocode.action;

import java.io.File;
import java.util.List;

import com.dalin.common.clazz.Clazz;
import com.dalin.common.clazz.Interfazz;
import com.dalin.common.utils.ExcelUtils;
import com.dalin.common.utils.FileUtils;
import com.dalin.common.utils.TextUtils;
import com.dalin.framework.action.StrutsTwoAction;
import com.dalin.platform.autocode.service.AutocodeService;
import com.dalin.platform.autocode.vo.BeanInfoVo;
import com.dalin.platform.etl.model.EtlDatabaseInfoEntity;
import com.dalin.platform.etl.model.EtlTableInfoEntity;
import com.dalin.platform.etl.service.EtlService;
import com.dalin.platform.loa.LoaConst;
import com.dalin.platform.pub.PlatContext;

/*****************************************************************************
 * @content:                                          *
 * @author : 那建林                                                          *
 * @crtDate: 2009-11-11                                                     *
 ****************************************************************************/
public class BuildCrudCodeAction extends StrutsTwoAction {
	private AutocodeService autocodeService; // 
	private EtlService etlService; // 
	private Long databaseId;
	private File excelFile;
	
	public String execute() throws Exception {
		try {
			etlService.synDbInfoStructure(databaseId); // synchronize
			EtlDatabaseInfoEntity dbEnty = PlatContext.getDao()
					.findObjById(EtlDatabaseInfoEntity.class, databaseId);
			List<EtlTableInfoEntity> tableList = dbEnty.getTableInfoEntitys();
	
			String tempPath = LoaConst.getFileInfoParam("tempSavedPath");
			File f = new File(tempPath);
			FileUtils.deleteFiles(f);
			f.mkdirs();
			if (excelFile == null) {
				for (EtlTableInfoEntity table : tableList) {
					BeanInfoVo vo = new BeanInfoVo();
					vo.setSavedPath(tempPath);
					vo.setTableId(table.getTableId());
					buildOne(vo);
				}
				return null;
			}
			List<List<String>> dataList = ExcelUtils.readAll(excelFile, 0);
			List<String> flagRow = dataList.get(1);
			for (EtlTableInfoEntity table : tableList) {
				BeanInfoVo vo = new BeanInfoVo();
				vo.setSavedPath(tempPath);
				vo.setTableId(table.getTableId());
				for (int i = 2; i < dataList.size(); i++) {
					boolean ot = false;
					List<String> row = dataList.get(i);
					for (int j = 0; j < flagRow.size(); j++) {
						String flagColumnValue = flagRow.get(j);
						String cv = row.get(j);
						if ("tableName".equals(flagColumnValue)) {
							if (table.getTableName().equals(cv)) {
								ot = true;
							}
						}
					}
					if (ot) {
						for (int j = 0; j < flagRow.size(); j++) {
							String flagColumnValue = flagRow.get(j);
							String cv = row.get(j);
							if ("javaPackageName".equals(flagColumnValue)) {
								vo.setJavaPackageName(cv);
							} else if ("annotationPackageName".equals(flagColumnValue)) {
								vo.setAnnotationPackageName(cv);
							} else if ("conditionPackageName".equals(flagColumnValue)) {
								vo.setConditionPackageName(cv);
							} else if ("serviceInterfacePackageName".equals(flagColumnValue)) {
								vo.setServiceInterfacePackageName(cv);
							} else if ("actionPackageName".equals(flagColumnValue)) {
								vo.setActionPackageName(cv);
							} else if ("actionServiceInterfaceName".equals(flagColumnValue)) {
								vo.setActionServiceInterfaceName(cv);
							} else {
								row.add("列(" + flagColumnValue+ ")添加失败");
							}
						}
						dataList.remove(row);
						i--;
					}
				}
				buildOne(vo);
			}
			exportExcel(dataList, "sheet1", "errorData");
		} catch (Exception e) {
			e.printStackTrace();
			setResContent(e);
		}
		return null;
	}

	private void buildOne(BeanInfoVo vo) throws Exception {
		// VO值对象
		Clazz myClazz = autocodeService.getJavaClazz(
				vo.getTableId(), vo.getJavaPackageName());
		overwriteTextFile(vo.getSavedPath() + "vo/", myClazz);
	
		// Annotation值对象
		Clazz annotationClazz = autocodeService.getAnnotationClazz(
				vo.getTableId(), vo.getAnnotationPackageName());
		overwriteTextFile(vo.getSavedPath() + "entity/", annotationClazz);
		
		// Condition查询条件对象
		myClazz = autocodeService.getConditionClazz(
				vo.getTableId(), vo.getConditionPackageName());
		overwriteTextFile(vo.getSavedPath() + "condition/", myClazz);
		
		// service接口类
		Interfazz fazz = autocodeService.getServiceInterfaceClazz(
				vo.getTableId(), vo.getServiceInterfacePackageName());
		TextUtils.overwriteToText(fazz.toString(),
				new File(vo.getSavedPath() + "service/" + fazz.getInterfaceName() + ".java"), "UTF-8");
		
		// service接口实现类
		Clazz serviceImpleClazz = autocodeService.getServiceImpleClazz(
				vo.getTableId(), vo.getServiceInterfacePackageName() + ".imple");
		overwriteTextFile(vo.getSavedPath() + "service/", serviceImpleClazz);
		
		// 增加修改action类
		Clazz addModActionClazz = autocodeService.getAddModActionClazz(
				vo.getActionServiceInterfaceName(), vo.getTableId(), vo.getActionPackageName());
		overwriteTextFile(vo.getSavedPath() + "action/", addModActionClazz);
		
		// 删除功能action类
		Clazz delActionClazz = autocodeService.getDelActionClazz(
				vo.getActionServiceInterfaceName(),
				vo.getTableId(), vo.getActionPackageName());
		overwriteTextFile(vo.getSavedPath() + "action/", delActionClazz);
	
		// 查找操作的action类
		Clazz findActionClazz = autocodeService.getFindActionClazz(vo.getActionServiceInterfaceName(), vo.getTableId(), vo.getActionPackageName());
		overwriteTextFile(vo.getSavedPath() + "action/", findActionClazz);
		
		// 查询列表操作的action类
		Clazz queryActionClazz = autocodeService.getQueryActionClazz(vo.getActionServiceInterfaceName(), vo.getTableId(), vo.getActionPackageName());
		overwriteTextFile(vo.getSavedPath() + "action/", queryActionClazz);
		
		
		// jsp列表页面
		String gridJspContentStr = autocodeService.getGridJspContent(vo.getTableId());
		TextUtils.overwriteToText(gridJspContentStr,
				new File(vo.getSavedPath() + "jsp/" + queryActionClazz.getClassName() + vo.getGridJspName()), "UTF-8");
		
		// jsp添加修改页面
		String addModJspContentStr = autocodeService.getAddModJspContent(vo.getTableId());
		TextUtils.overwriteToText(addModJspContentStr,
				new File(vo.getSavedPath() + "jsp/" + queryActionClazz.getClassName() + vo.getAddModJspName()), "UTF-8");
		
		// 其他配置文件
		StringBuffer otherConfig = new StringBuffer();
		otherConfig.append("<mapping class=\"")
				.append(vo.getAnnotationPackageName()+".")
				.append(annotationClazz.getClassName()).append("\" />\n\n");
		otherConfig.append("<bean id=\"")
				.append(vo.getActionServiceInterfaceName())
				.append("\" parent=\"txProxyTemplate\">\n");
		otherConfig.append("	<property name=\"target\">\n");
		otherConfig.append("		<bean class=\"")
				.append(vo.getServiceInterfacePackageName())
				.append(".imple.").append(serviceImpleClazz.getClassName())
				.append("\" autowire=\"byName\" />\n");
		otherConfig.append("	</property>\n");
		otherConfig.append("</bean>\n\n");
		
		
		otherConfig.append("<bean id=\"").append(addModActionClazz
				.getClassName()).append("\" class=\"")
				.append(vo.getActionPackageName()+".")
				.append(addModActionClazz.getClassName())
				.append("\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"").append(delActionClazz
				.getClassName()).append("\" class=\"")
				.append(vo.getActionPackageName()+".")
				.append(delActionClazz.getClassName())
				.append("\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"").append(findActionClazz
				.getClassName()).append("\" class=\"")
				.append(vo.getActionPackageName()+".")
				.append(findActionClazz.getClassName())
				.append("\" scope=\"prototype\" autowire=\"byName\" />\n");
		otherConfig.append("<bean id=\"").append(queryActionClazz
				.getClassName()).append("\" class=\"")
				.append(vo.getActionPackageName()+".")
				.append(queryActionClazz.getClassName())
				.append("\" scope=\"prototype\" autowire=\"byName\" />\n\n");
		
		otherConfig.append("<action name=\"")
				.append(getReqActionUrl(addModActionClazz.getClassName()))
				.append("\" class=\"").append(addModActionClazz.getClassName())
				.append("\" />\n");
		otherConfig.append("<action name=\"")
				.append(getReqActionUrl(delActionClazz.getClassName()))
				.append("\" class=\"").append(delActionClazz.getClassName())
				.append("\" />\n");
		otherConfig.append("<action name=\"")
				.append(getReqActionUrl(findActionClazz.getClassName()))
				.append("\" class=\"").append(findActionClazz.getClassName())
				.append("\" />\n");
		otherConfig.append("<action name=\"")
				.append(getReqActionUrl(queryActionClazz.getClassName()))
				.append("\" class=\"").append(queryActionClazz.getClassName())
				.append("\" />\n");
		TextUtils.overwriteToText(otherConfig.toString(),
				new File(vo.getSavedPath() + "otherConfig/" + annotationClazz.getClassName() + "otherConfig.xml"), "UTF-8");
	}
	private void overwriteTextFile(String savedPath, Clazz myClazz) throws Exception {
		TextUtils.overwriteToText(myClazz.toString(),
				new File(savedPath + myClazz.getClassName() + ".java"), "UTF-8");
	}
	private String getReqActionUrl(String actionClassName) throws Exception {
		actionClassName = actionClassName.substring(0, actionClassName.length() - 6);
		return actionClassName.substring(0, 1).toLowerCase()
				+ actionClassName.substring(1);
	}
	
	
	
	public AutocodeService getAutocodeService() {
		return autocodeService;
	}

	public void setAutocodeService(AutocodeService autocodeService) {
		this.autocodeService = autocodeService;
	}

	public Long getDatabaseId() {
		return databaseId;
	}

	public void setDatabaseId(Long databaseId) {
		this.databaseId = databaseId;
	}
	public File getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(File excelFile) {
		this.excelFile = excelFile;
	}

	public EtlService getEtlService() {
		return etlService;
	}

	public void setEtlService(EtlService etlService) {
		this.etlService = etlService;
	}
}
